/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Patrick van der Velde
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Diagnostics;

namespace dnAnalytics.LinearAlgebra.Solvers
{
    /// <summary>
    /// Defines an <see cref="IIterationStopCriterium"/> that monitors residuals for NaN's.
    /// </summary>
    public sealed class FailureStopCriterium : IIterationStopCriterium
    {
        /// <summary>
        /// Defines the default last iteration number. Set to -1 because iterations normally
        /// start at 0.
        /// </summary>
        private const int sm_DefaultLastIterationNumber = -1;

        /// <summary>
        /// The default status.
        /// </summary>
        private static readonly ICalculationStatus sm_DefaultStatus = new CalculationIndetermined();

        /// <summary>
        /// The status of the calculation
        /// </summary>
        private ICalculationStatus m_Status = sm_DefaultStatus;

        /// <summary>
        /// The iteration number of the last iteration.
        /// </summary>
        private int m_LastIteration = sm_DefaultLastIterationNumber;

        /// <summary>
        /// Creates an instance of the <c>FailureStopCriterium</c> class.
        /// </summary>
        public FailureStopCriterium()
        { }

        /// <summary>
        /// Determines the status of the iterative calculation based on the stop criteria stored
        /// by the current <c>IIterationStopCriterium</c>.
        /// </summary>
        /// <param name="iterationNumber">The number of iterations that have passed so far.</param>
        /// <param name="solutionVector">The vector containing the current solution values.</param>
        /// <param name="sourceVector">The right hand side vector.</param>
        /// <param name="residualVector">The vector containing the current residual vectors.</param>
        /// <returns>
        ///   An <c>ICalculationStatus</c> which indicates what the status of the iterative 
        ///   calculation is according to the current <c>IIterationStopCriterium</c>.
        /// </returns>
        /// <remarks>
        /// The individual stop criteria may internally track the progress of the calculation based
        /// on the invocation of this method. Therefore this method should only be called if the 
        /// calculation has moved forwards at least one step.
        /// </remarks>
        public void DetermineStatus(int iterationNumber, Vector solutionVector, Vector sourceVector, Vector residualVector)
        {
            if (iterationNumber < 0)
            {
                throw new ArgumentOutOfRangeException("iterationNumber");
            }

            if (solutionVector == null)
            {
                throw new ArgumentNullException("solutionVector");
            }

            if (residualVector == null)
            {
                throw new ArgumentNullException("residualVector");
            }

            if (solutionVector.Count != residualVector.Count)
            {
                throw new NotConformableException();
            }

            if (m_LastIteration >= iterationNumber)
            {
                // We have already stored the actual last iteration number
                // For now do nothing. We only care about the next step.
                return;
            }

            // Store the infinity norms of both the solution and residual vectors
            double residualNorm = residualVector.InfinityNorm();
            double solutionNorm = solutionVector.InfinityNorm();

            if ((Double.IsNaN(solutionNorm)) || (double.IsNaN(residualNorm)))
            {
                SetStatusToFailed();
            }
            else
            {
                SetStatusToRunning();
            }

            m_LastIteration = iterationNumber;
        }

        private void SetStatusToFailed()
        {
            if (!(m_Status is CalculationFailure))
            {
                m_Status = new CalculationFailure();
            }
        }

        private void SetStatusToRunning()
        {
            if (!(m_Status is CalculationRunning))
            {
                m_Status = new CalculationRunning();
            }
        }

        /// <summary>
        /// Returns the current calculation status.
        /// </summary>
        public ICalculationStatus Status
        {
            [DebuggerStepThrough]
            get
            {
                return m_Status;
            }
        }

        /// <summary>
        /// Resets the <c>IIterationStopCriterium</c> to the pre-calculation state.
        /// </summary>
        public void ResetToPrecalculationState()
        {
            m_Status = sm_DefaultStatus;
            m_LastIteration = sm_DefaultLastIterationNumber;
        }

        /// <summary>
        /// Returns the <c>StopLevel</c> which indicates what sort of stop criterium this
        /// <c>IIterationStopCriterium</c> monitors.
        /// </summary>
        /// <value>Returns <see cref="dnAnalytics.LinearAlgebra.Solvers.StopLevel.CalculationFailure"/>.</value>
        public StopLevel StopLevel
        {
            [DebuggerStepThrough]
            get
            {
                return StopLevel.CalculationFailure;
            }
        }

        /// <summary>
        /// Clones the current <c>FailureStopCriterium</c> and its settings.
        /// </summary>
        /// <returns>A new instance of the <c>FailureStopCriterium</c> class.</returns>
        public IIterationStopCriterium Clone()
        {
            return new FailureStopCriterium();
        }

        object ICloneable.Clone()
        {
            return Clone();
        }
    }
}
